package net.obxlabs.tweetpad.behaviour;

import net.nexttext.*;
import net.nexttext.behaviour.*;
import net.nexttext.property.*;

/**
 * Removes the TextObjectGroup from the hierarchy and places all its children at its level.
 */
public class BreakApart extends AbstractAction {
	private int limit;
	
	public BreakApart(int limit) {
		this.limit = limit;
	}
	
	public ActionResult behave(TextObject to) {
		if (!(to instanceof TextObjectGroup)) {
			// only works on TextObjectGroups
			to.getBook().log("BreakApart only works on TextObjectGroups!");
			return new ActionResult(true, true, false);
		}
		
		TextObjectGroup tog = (TextObjectGroup)to;
		if (tog.getNumChildren() < 1) {
			// only works when there's children
			to.getBook().log("BreakApart only works if you have children!");
			return new ActionResult(true, true, false);
		}
		
		System.out.println("Breaking '"+to+"' apart!");
		
		// set the property on all the child glyphs
		for (TextObjectGlyphIterator i = tog.glyphIterator(); i.hasNext();) {
			setDescendProperty(i.next());
		}
		
		/*for (TextObject child = tog.getLeftMostChild(); child != null; child = tog.getLeftMostChild()) {
			if (child instanceof TextObjectGlyph) {
				// don't handle TextObjectGlyphs
				// the tree should be structured so that each glyph is alone in a group
				continue;
			} else {
				// move the TextObject a level up in the tree
				child.detach();
				tog.attachToLeft(child);
				
				// adjust its position
				child.getPosition().add(tog.getPosition().get());
			}
		}
		
		// delete the group
		top.getBook().removeObject(tog);
		
		// if a SetHeight is acting on this group, adjust its value
		if (level != null) {
			level.decOffset();
		}*/
		
		return new ActionResult(true, true, false);
	}
	
	public void setDescendProperty(TextObject to) {
		NumberProperty descendProp = (NumberProperty)to.getProperty("Descend");
		if (descendProp == null) {
			// init the property
			to.init("Descend", new NumberProperty(1));
		} else {
			int curr = (int)descendProp.get();
			if (curr > limit) {
				// increment the property
				descendProp.set(++curr);
			}
		}
	}
}
